<!-- 任务委托 - 项目负责人 -->
<template>
  <view class="page">
    <u--form
      labelPosition="top"
      :model="basicForm"
      ref="form1"
      labelWidth="auto"
      :labelStyle="{
        fontSize: '14px',
        color: '#B2B2B2',
        lineHight: '20px',
      }"
    >
		<view class="basic-style">
		    <view class="basic-title basic-border">费用类别</view>
		    <view class="py-1 space-y-1" style="width: 100%">
					<u-form-item label="费用类别" props="feeCategory" required>
			  <h-radio-group disabled style="padding: 12upx 0;" v-model="basicForm.feeCategory" dictName="fee_category"/>
			</u-form-item>
			<text v-text="basicForm.feeCategory=='0'?'职工薪酬类报销（不含集中采购的节日福利）':basicForm.feeCategory=='1'?'需签订合同的采购类报销':'其他场景'"/>
		    </view>
		</view>
      <view class="basic-style">
        <view class="basic-title basic-border">基础信息</view>
        <u-form-item label="单据编号" prop="billNo" :borderBottom="false">
          <u--input disabled placeholder="请输入单据编号" v-model="basicForm.billNo" border="surround"></u--input>
        </u-form-item>
        <u-form-item label="填表时间" prop="createTime" :borderBottom="false">
          <u--input
            v-model="basicForm.createTime"
            disabled
            placeholder="请选择填表时间"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></u--input>
        </u-form-item>
				<u-form-item label="费用所属团队" prop="teamId" :borderBottom="false">
				<h-select-team-input
					disabled
					style="width: 100%"
					v-model="basicForm.teamId"
					objectField="basicForm.teamId"
					placeholder="请选择费用所属团队"
					border="surround"
					suffixIcon="arrow-down-fill"
					:suffixIconStyle="{ color: '#B2B2B2' }"
					:tdlx="3"
				></h-select-team-input>
			</u-form-item>
			<u-form-item label="申请公司" prop="applicant" :borderBottom="false">
				<h-select-company-input
					disabled
					style="width: 100%"
					v-model="basicForm.applicant"
					border="surround"
					placeholder="请选择申请公司"
					suffixIcon="arrow-down-fill"
					:suffixIconStyle="{ color: '#B2B2B2' }"
					@input="companyChange"
					objectField="basicForm.applicant"
				></h-select-company-input>
			</u-form-item>
			<block v-if="basicForm.teamYear=='2023'">
				<u-form-item label="费用所属年度" prop="billCategory" :borderBottom="false">
					<h-dict-select
						style="width: 100%"
						v-model="basicForm.teamYear"
						disabled
						placeholder="请选择费用所属年度"
						dictName="tdnd_type"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
					></h-dict-select>
				</u-form-item>
			</block>
        <u-form-item label="报销人" prop="proposer" :borderBottom="false">
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="basicForm.proposer"
            placeholder="请选择报销人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="basicForm.proposer"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="所在部门" prop="proposerDeptId" :borderBottom="false">
          <h-select-depart-input
            disabled
            v-model="basicForm.proposerDeptId"
            :departName="basicForm.proposerDeptText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="basicForm.proposerDeptText"
          ></h-select-depart-input>
        </u-form-item>

			<u-form-item label="团队费用类别" prop="teamFeeCategory" :borderBottom="false" required>
				<h-dict-select
					style="width: 100%"
					v-model="basicForm.teamFeeCategory"
					placeholder="请选择团队费用类别"
					dictName="team_fee_category"
					suffixIcon="arrow-down-fill"
					:suffixIconStyle="{ color: '#B2B2B2' }"
				></h-dict-select>
			</u-form-item>

			<u-form-item label="单据类型" prop="billCategory" :borderBottom="false">
				<h-dict-select
					style="width: 100%"
					v-model="basicForm.billCategory"
					disabled
					placeholder="请选择单据类型"
					dictName="bill_category"
					suffixIcon="arrow-down-fill"
					:suffixIconStyle="{ color: '#B2B2B2' }"
				></h-dict-select>
			</u-form-item>
			<u-form-item label="本次是否付款" prop="isPay" :borderBottom="false">
				<h-dict-select
					style="width: 100%"
					v-model="basicForm.isPay"
					disabled
					placeholder="请选择本次是否付款"
					dictName="is_pay"
					suffixIcon="arrow-down-fill"
					:suffixIconStyle="{ color: '#B2B2B2' }"
				></h-dict-select>
			</u-form-item>
			<u-form-item label="本次付款金额(元)" prop="payAmount" required>
					<h-money-input :disabled="basicForm.isPay=='0'" placeholder="请输入本次付款金额" v-model="basicForm.payAmount"></h-money-input>
			</u-form-item>
			<u-form-item label="累计报销金额(元)" prop="accumulateAmount" :borderBottom="false">
				<u--input disabled placeholder="请输入累计报销金额" v-model="basicForm.accumulateAmount" border="surround"></u--input>
			</u-form-item>
			<u-form-item label="本次累计冲账金额(元)" prop="chargedAmount" :borderBottom="false">
				<u--input disabled placeholder="请输入本次累计冲账金额" v-model="basicForm.chargedAmount" border="surround"></u--input>
			</u-form-item>
			<u-form-item label="是否使用商务卡" prop="isUseBusinessCard" required>
				<h-select-input-tag
					class="w-100"
					disabled
					v-model="basicForm.isUseBusinessCard"
					objectField="model.isUseBusinessCard"
					placeholder="请选择是否使用商务卡"
					border="surround"
					suffixIcon="arrow-down-fill"
					:suffixIconStyle="{ color: '#B2B2B2' }"
					dictName="YES_OR_NO"/>
			</u-form-item>
			<u-form-item label="报销说明" prop="applyExplain" required>
			  <u--textarea :confirm-type="null" maxlength="500" count v-model="basicForm.applyExplain" placeholder="请输入报销说明"/>
			</u-form-item>
			<!-- <u-form-item label="费用类别" props="feeCategory" required>
			  <h-radio-group disabled style="padding: 12upx 0;" v-model="basicForm.feeCategory" dictName="fee_category"/>
			</u-form-item>
			<text v-text="basicForm.feeCategory=='0'?'职工薪酬类报销（不含集中采购的节日福利）':basicForm.feeCategory=='1'?'需签订合同的采购类报销':'其他场景'"/> -->
		</view>
			
		<view class="basic-style">
			<view class="basic-title basic-border">费用报销信息</view>
			<!-- 工资福利类 -->
			
			<salaryModel ref='salaryRef' :showButton="false" :showFlowSubmitButton="true" @inputAmount="inputAmount" :feeCategory='basicForm.feeCategory'/>
			<!-- 采购类 -->
			<!-- getInformation => 获取账户信息 projectChange => 选择项目 -->
			<purchaseModel ref="purchaseRef" :showFlowSubmitButton="true" @inputAmount="inputAmount" @getInformation="getInformation" @projectChange="projectChange" :teamId='basicForm.teamId' :companyId='basicForm.applicant' :feeCategory='basicForm.feeCategory'/>
			<!-- 费用类 -->
			<costModel ref='costRef' :showButton="false" :showFlowSubmitButton="true" :isRelProject='basicForm.isRelProject' @getDailyFeeInfoList="getDailyFeeInfoList" @inputAmount="inputAmount" @change="changeCostRef" :teamId='basicForm.teamId' :companyId='basicForm.applicant' :feeCategory='basicForm.feeCategory'/>
			
		</view>

		<view class="basic-style">
			<u-form-item label="结算方式" prop="settleType" required v-if="basicForm.isPay=='1'">
					<h-dict-select
						disabled
						style="width: 100%" 
						v-model="basicForm.settleType" 
						placeholder="请选择结算方式" 
						dictName="settle_type" 
						suffixIcon="arrow-down-fill" 
						:suffixIconStyle="{color: '#B2B2B2'}"
					></h-dict-select>
			</u-form-item>
			<!-- 转账才需要填写 -->
			<template v-if="basicForm.settleType=='0'">
				<u-form-item label="转账类型" prop="transferType" required v-if="basicForm.isPay=='1'">
						<h-dict-select
							style="width: 100%" 
							v-model="basicForm.transferType" 
							placeholder="请选择转账类型" 
							dictName="transfer_type"
							suffixIcon="arrow-down-fill" 
							:suffixIconStyle="{color: '#B2B2B2'}"
							disabled
						></h-dict-select>
				</u-form-item>
				<u-form-item label="收款户名" prop="accountName" required v-if="basicForm.transferType">
					<h-select-person-input
					  v-model="basicForm.accountName"
						v-if="basicForm.transferType=='1'"
						objectField="basicForm.accountName"
					  class="w-100"
					  placeholder="请选择收款户名"
					  border="surround"
					  suffixIcon="arrow-down-fill"
					  :suffixIconStyle="{color: '#B2B2B2'}"
					  disabled/>
					  <h-select-customer-input-popup
							v-if="basicForm.transferType=='2'"
							:isFinance="true"
							style="width: 100%"
							v-model="basicForm.accountName"
							objectField="basicForm.accountName"
							commercialType="2"
							placeholder="请选择关联往来单位"
							suffixIcon="arrow-down-fill"
							:suffixIconStyle="{ color: '#B2B2B2' }"
							:isJudge='true'
							disabled
							border="surround"
						/>
				</u-form-item>
				<template v-if="basicForm.accountName">
					<u-form-item label="收款方开户行" prop="bankName" required>
					    <u--input disabled v-model="basicForm.bankName" placeholder="请输入收款方开户行"/>
					</u-form-item>
					<u-form-item label="开户行联行号" prop="cnapsCode" required>
					    <u--input v-model="basicForm.cnapsCode" disabled placeholder="请输入收款方开户行"/>
					</u-form-item>
					<u-form-item label="收款方银行账户" prop="accountNo" required>
					    <u--input disabled v-model="basicForm.accountNo" placeholder="请输入收款方银行账户" :maxlength="32"/>
					</u-form-item>
					<u-form-item label="打款附言" prop="postscript" required>
							<u--textarea :confirm-type="null" maxlength="200" count v-model="basicForm.postscript" placeholder="请输入打款附言"/>
					</u-form-item>
				</template>
			</template>
			<template v-if="basicForm.isPay">
				<u-form-item label="冲账单据类型" prop="relBillType" :required="basicForm.isPay==0">
					<h-dict-select
						v-if="basicForm.feeCategory=='2' && basicForm.isRelProject=='1' && this.$refs.costRef.costList.length!=0"
						style="width: 100%" 
						disabled
						v-model="basicForm.relBillType" 
						placeholder="请选择冲账单据类型" 
						dictName="rel_bill_type" 
						suffixIcon="arrow-down-fill" 
						:suffixIconStyle="{color: '#B2B2B2'}"
					></h-dict-select>
					<h-dict-select
						v-else
						disabled
						style="width: 100%" 
						v-model="basicForm.relBillType" 
						placeholder="请选择冲账单据类型" 
						dictName="rel_bill_type_no_project" 
						suffixIcon="arrow-down-fill" 
						:suffixIconStyle="{color: '#B2B2B2'}"
					></h-dict-select>
				</u-form-item>
				<u-form-item label="关联单据单号" prop="relBillId" v-if="basicForm.relBillType==3" required>
						<h-select-borrowbill-input-popup
							v-if="basicForm.relBillType=='1'"
							disabled
							:teamId="basicForm.teamId"
							:companyId="basicForm.applicant"
							:proposer="userInfo.empId"
							settleAccounts="0"
							checkStatus="2"
							class="w-100"
							v-model="basicForm.relBillId"
							placeholder="请选择借款单单据"
							border="surround"
							suffixIcon="arrow-down-fill"
							:suffixIconStyle="{ color: '#B2B2B2' }"
							@realChange="handleApplicantChange"/>
					<h-select-finance-deposit-bill-input
						v-if="basicForm.relBillType=='3'"
						disabled
						v-model="basicForm.relBillId"
						:teamId="basicForm.teamId"
						:projectId="this.$refs.costRef.costList&&this.$refs.costRef.costList.length?this.$refs.costRef.costList[0].projectId:''" 
						:applicant="basicForm.applicant"
						objectField="basicForm.relBillId"
						style="width: 100%;"
						placeholder="请选择保证金单据"
						@input="handleApplicantChange"
					>
					</h-select-finance-deposit-bill-input>
				</u-form-item>
				<view v-if="basicForm.relBillType==1||basicForm.relBillType==2">
					<view class="trip-form-data">
						<u-collapse ref="collapseView3">
							<u-collapse-item :title="`${basicForm.relBillType==1?'借款单单据':'付款单单据'}${index + 1}`" v-for="(item, index) in basicForm.chargedInfoList"
								:key="index">
								<ReversePaymentFormInfo :showButton="false" :showFlowSubmitButton="true" :relBillType="basicForm.relBillType" :item="item" :index="index" @edit="handleEditReverseForm" />
							</u-collapse-item>
						</u-collapse>
					</view>
					<u-popup :round="10" mode="bottom" :closeOnClickOverlay="false" :show="showReverseModal"
						@close="closeReverseModal" @open="openReverseModal">
						<ReversePaymentForm :childSource="basicForm.chargedInfoList" :formBpm="true" :teamId="basicForm.teamId" :relBillType="basicForm.relBillType" :applicant="basicForm.applicant" ref="ReverseForm" :index="index" @submit="handleReverseSubmit" @close="showReverseModal = false" />
					</u-popup>
				</view>
				<template v-if="basicForm.relBillType=='3'">
					<u-form-item label="保证金总额(元)" prop="depositRemittanceAmount">
							<u--input disabled v-model="basicForm.depositRemittanceAmount" placeholder="请输入保证金总额"/>
					</u-form-item>
					<u-form-item label="服务费(元)" prop="depositServiceCharge">
							<u--input disabled v-model="basicForm.depositServiceCharge" placeholder="请输入服务费"/>
					</u-form-item>
					<u-form-item label="利息金额(元)" prop="depositInterestAmount">
							<u--input disabled v-model="basicForm.depositInterestAmount" placeholder="请输入利息金额"/>
					</u-form-item>
					<u-form-item label="归还金额(元)" prop="depositReturnAmount">
							<u--input disabled v-model="basicForm.depositReturnAmount" placeholder="请输入归还金额"/>
					</u-form-item>
					<u-form-item label="未归还金额(元)" prop="depositUnreturnAmount">
							<u--input disabled v-model="basicForm.depositUnreturnAmount" placeholder="请输入未归还金额"/>
					</u-form-item>
				</template>
			</template>
    </view>
		</u--form>

    <!-- 附件 -->
    <view class="basic-style">
      <view class="basic-title basic-border">附件信息</view>
			<view class="py-1 space-y-1" style="width: 100%">
			  <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
			  <!-- <h-upload-file v-model="basicForm.attachments" :isIcon="false"/> -->
			  <file-list v-if="basicForm.attachments" v-model="basicForm.attachments" :isDelete="false"/>
			</view>
    </view>

    <view class="space-x-1 px-1 btn_position">
    	<backButton  @onSubmit="onSubmit" :nodeObj="nodeObj" :model="model" :resultObj="resultObj"></backButton>
    </view>
    <view style="height: 100rpx;"></view>
		
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
import http from '@/utils/request'
import fileList from './components/fileList.vue'
import backButton from '@/components/backButton.vue'
import salaryModel from '@/pages/finance/reimComp/salaryModel.vue'
import purchaseModel from '@/pages/finance/reimComp/purchaseModel.vue'
import costModel from '@/pages/finance/reimComp/costModel.vue'
import ReversePaymentForm from '@/pages/finance/components/ReversePaymentForm.vue'
import ReversePaymentFormInfo from '@/pages/finance/components/ReversePaymentFormInfo.vue'
import { filterMultiDictText, initDictOptions } from '@/utils/JDictSelectUtil.js'
	import {feeReimburseEdit} from '@/api/finance/ErpFinanceRepaymentSlipForm'
import {
	getProcessTaskTransInfo, // 流程流转
  queryByIdreimbursementBill, // 根据id查询详情
} from '@/api/index.js'
import { BASE_URL } from '@/utils/baseUrl.js'
import { mapState } from 'vuex'
import Decimal from 'decimal.js'
export default {
  components: {
    fileList,
		backButton,
		salaryModel,
		purchaseModel,
		costModel,
		ReversePaymentFormInfo,
		ReversePaymentForm
  },
  data() {
    return {
			resultObj: {}, // 流程图流转信息
      isFirst: true, // 是否第一次进入此页面
      filterMultiDictText,
      initDictOptions,
      dictOptions: {},
      isSubmit: false,
      basicForm: {},
      nodeObj: {},
      tabvalue: '',
      id: '', // 详情id值
      model: {},
			index: null,
			showReverseModal: false,
			dailyFeeInfoList: [], // 费用类列表数据
			childForm: {}
    }
  },
  onLoad(options) {
    // 获取用户信息
    this.model = JSON.parse(decodeURIComponent(options.item))
    this.initDictConfig()
    var that = this
    // #ifdef APP-NVUE
    var eventChannel = this.$scope.eventChannel // 兼容APP-NVUE
    // #endif
    // #ifndef APP-NVUE
    var eventChannel = this.getOpenerEventChannel()
    // #endif
    // 监听sendMessage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('sendMessage', function (data) {
      that.tabvalue = data.tabvalue
      that.nodeObj = JSON.parse(decodeURIComponent(data.nodeObj))
      that.id = that.nodeObj.dataId
      that.loadData(that.nodeObj.dataId)
			that.getProcessTaskTrans(that.model.id)
    })
  },
  provide() {
  	return {
  		dictOptions: this.dictOptions,
  	}
  },
	computed: {
	  ...mapState(['userInfo']),
	},
  methods: {
    async loadData(id) {
      let res = await queryByIdreimbursementBill({id:this.id})
      if(res.success){
      	let { salaryFeeInfoList,purchaseyFeeInfo,dailyFeeInfoList}= await res.result
      	
      	this.basicForm = Object.assign({}, res.result)
      	// this.basicForm.payAmount = this.basicForm.payAmount + ''
      	if(res.result.feeCategory=='0'){
					this.timer2 = setTimeout(() => {
						clearTimeout(this.timer2)
						this.timer2 = null
						// 选择了 工资福利类
						this.$nextTick(() => {
							salaryFeeInfoList.map(value => {
								value.bigCategoryName = filterMultiDictText(this.dictOptions['bigCategory'], value.bigCategory + '')
								value.smallCategoryName = filterMultiDictText(this.dictOptions['smallCategory'], value.smallCategory + '')
								value.isSpecial_dictText = filterMultiDictText(this.dictOptions['isSpecial'], value.isSpecial + '')
							})
							this.$refs.salaryRef.salaryFeeInfoList= salaryFeeInfoList
						})
					}, 500)
      	}else if(res.result.feeCategory=='1'){
      		// 选择了 采购类
      		this.$refs.purchaseRef.purchaseyFeeInfo= purchaseyFeeInfo
      		this.$refs.purchaseRef.changeBigCategory('01', {id: purchaseyFeeInfo.bigCategory})
					this.$refs.purchaseRef.specialRules() // 发票类型验证规则
      	}else if(res.result.feeCategory=='2'){
      		// 选择了 费用类
      		this.basicForm.isRelProject = dailyFeeInfoList[0].projectId?'1':'0'
      		this.timer = setTimeout(() => {
      			clearTimeout(this.timer)
      			this.timer = null
      			this.$nextTick(() => {
      				dailyFeeInfoList = this.getCostList(dailyFeeInfoList)
      				this.$refs.costRef.costList = dailyFeeInfoList
      				this.dailyFeeInfoList = dailyFeeInfoList // 获取费用类列表数据
      			})
      		}, 500)
      	}
      	if(res.result.relBillType&&(res.result.relBillType==1||res.result.relBillType==2)){
      		http.get('/api/erp/finance/reimbursement/erpFinanceReimbursementChargedBillInfo/queryBillById',{ billId: res.result.id }).then(resspon => {
      			if(resspon.success){
      				let data = resspon.result;
      				if (data.records != undefined) {
      					data = data.records
      				}
      				this.basicForm.chargedInfoList = data || []
      			}
      		})
      	} else {
      		this.basicForm.chargedInfoList = []
      	}
      }
    },
		// 查询流程流转信息 -- 获取下一节点信息
		getProcessTaskTrans(taskId){
			getProcessTaskTransInfo({ taskId }).then(res => {
				if(res.success){
					this.resultObj = res.result
				} else {
					this.$refs.uToast.show({
						message: res.message,
						type: 'error'
					})
				}
			}).catch(err => {
				console.log(err);
			})
		},
		getCostList (item = []) {
			if (item && item.length) {
				for (var i = 0; i < item.length; i++) {
					item[i].projectName = filterMultiDictText(this.dictOptions['projectId'], item[i].projectId + '')
					item[i].relContractId_dictText = filterMultiDictText(this.dictOptions['relContractId'], item[i].relContractId + '')
					item[i].taskCategory_dictText = filterMultiDictText(this.dictOptions['taskCategory'], item[i].taskCategory + '')
					item[i].bigCategoryName = filterMultiDictText(this.dictOptions['bigCategory'], item[i].bigCategory + '')
					item[i].smallCategoryName = filterMultiDictText(this.dictOptions['smallCategory'], item[i].smallCategory + '')
					item[i].isSpecial_dictText = filterMultiDictText(this.dictOptions['isSpecial'], item[i].isSpecial + '')
				}
			}
			return item
		},
		// 计算输入主表累计报销金额
		inputAmount(arg){
			if(arg==1){//工资福利
				// 计算累计报销金额
				if (this.$refs.salaryRef.salaryFeeInfoList && this.$refs.salaryRef.salaryFeeInfoList.length) {
					let salaryFeeInfoList= this.$refs.salaryRef.salaryFeeInfoList;
					let salaryFeeAmount=0;
					salaryFeeInfoList.forEach(item=>{
						salaryFeeAmount+= Number(item.amount);
					})
					this.$set(this.basicForm,'accumulateAmount', Number(salaryFeeAmount).toFixed(2));
				}
				
			}else if(arg==2){//采购
				// 累计报销金额
				if(this.$refs.purchaseRef.purchaseyFeeInfo.amount){
					this.$set(this.basicForm,'accumulateAmount', Number(this.$refs.purchaseRef.purchaseyFeeInfo.amount).toFixed(2));
				}
			}else if(arg==3){//费用
				// 累计报销金额
				if (this.$refs.costRef.costList && this.$refs.costRef.costList.length) {
					let costList=this.$refs.costRef.costList;
					let costListAmount=0;
					costList.forEach(item=>{
						costListAmount+= Number(item.amount);
					})
					// 累计报销金额
					this.$set(this.basicForm,'accumulateAmount',costListAmount.toFixed(2));
				}
			}
		},
		/**
		 * 报销新增点击确认
		 */
		handleReverseSubmit([data, index]) {
			this.showReverseModal = false
			if (typeof index === 'number') {
				this.$set(this.basicForm.chargedInfoList, index, {
					...data
				})
			} else {
				this.basicForm.chargedInfoList.push(data)
			}
			this.$refs.ReverseForm.dataSource = this.basicForm.chargedInfoList
			// 计算总金额
			this.handelCharedAmount()
			this.collapseView3Init()
		},
		handelCharedAmount(){
			let chargedAmount = 0
			this.basicForm.chargedInfoList.forEach(item=>{
				chargedAmount+=Number(item.chargedAmount);
			})
			this.basicForm.chargedAmount =  chargedAmount.toFixed(2)
		},
		closeReverseModal() {
			this.childForm = {}
			this.$refs.ReverseForm.reset()
			this.index = null
		},
		openReverseModal() {
			this.$refs.ReverseForm.basicForm = this.childForm
		},
		handleEditReverseForm([item, index]) {
			this.childForm = {
				...item
			}
			this.index = index
			this.showReverseModal = true
			this.collapseView3Init()
		},
		collapseView3Init() {
		  setTimeout(() => {
			this.$refs.collapseView3.init()
		  }, 500)
		},
		// 采购类点击切换项目
		projectChange () {
			// 当有采购合同时会清空收款信息：accountName、bankName、accountNo
			this.$set(this.basicForm,"accountName",'');
			this.$set(this.basicForm,"bankName",'');
			this.$set(this.basicForm,"cnapsCode",'');
			this.$set(this.basicForm,"accountNo",'');
		},
		// 采购类点击采购合同
		getInformation (accountName) {
			if (this.basicForm.settleType == '0' && this.basicForm.transferType == '2'){
				this.$set(this.basicForm,'accountName',accountName)
				
				let customerId = accountName
				this.getAccount(customerId)
			}
		},
		// 选择费用类是否关联项目
		changeCostRef (e) {
			this.$set(this.basicForm, 'isRelProject', e)
			// this.basicForm.isRelProject = e
		},
		
		// 获取费用类的列数据
		getDailyFeeInfoList (list) {
			this.dailyFeeInfoList = list
			if (list && list.length) {
				var projectId = list[0].projectId;
				if(this.basicForm.relBillType=='3'){
					//如果项目存在
					if(projectId){
						this.$set(this.basicForm, 'relBillType', '');
						this.$set(this.basicForm, 'depositRemittanceAmount', '');
						this.$set(this.basicForm, 'depositReturnAmount', '');
						this.$set(this.basicForm, 'depositServiceCharge', '');
						this.$set(this.basicForm, 'depositInterestAmount', '');
					}
				}
				
			} else {
				this.$set(this.basicForm, 'relBillType', '')
			}
		},
    initDictConfig() {
			initDictOptions('sys_category,name,code').then((res) => {
				if (res.success) {
					this.$set(this.dictOptions, 'bigCategory', res.result)
				}
			})
			initDictOptions('sys_category,name,code').then((res) => {
				if (res.success) {
					this.$set(this.dictOptions, 'smallCategory', res.result)
				}
			})
      initDictOptions('erp_omc_project,project_name,id').then((res) => {
      	if (res.success) {
      		this.$set(this.dictOptions, 'projectId', res.result)
      	}
      })
      initDictOptions('erp_finance_loan_bill,bill_no,id').then((res) => {
      	if (res.success) {
      		this.$set(this.dictOptions, 'relLoanBillId', res.result)
      	}
      })
      initDictOptions('erp_finance_payment_slip,bill_no,id').then((res) => {
      	if (res.success) {
      		this.$set(this.dictOptions, 'relPayBillId', res.result)
      	}
      })
      initDictOptions('erp_omc_contract_manager_final,htmc,id').then((res) => {
      	if (res.success) {
      		this.$set(this.dictOptions, 'relContractId', res.result)
      	}
      })
      initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
      	if (res.success) {
      		this.$set(this.dictOptions, 'teamManager', res.result)
      	}
      })
      initDictOptions('erp_omc_project_task,category_name,id').then((res) => {
      	if (res.success) {
      		this.$set(this.dictOptions, 'taskCategory', res.result)
      	}
      })
      initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
      	if (res.success) {
      		this.$set(this.dictOptions, 'teamId', res.result)
      	}
      })
      initDictOptions('cost_invoice_type').then((res) => {
      	if (res.success) {
      		this.$set(this.dictOptions, 'isSpecial', res.result)
      	}
      })
      // initDictOptions('yjgsnd').then((res) => {
      // 	if (res.success) {
      // 		this.$set(this.dictOptions, 'performanceAttributionYear', res.result)
      // 	}
      // })
    },
    showMessage(message) {
      uni.showToast({
        title: message,
        icon: 'none',
      })
    },
		//判断付款金额是否大于支付金额
		handleAmount(){
			let model=this.basicForm;
			let accumulateAmount=model.accumulateAmount
			let chargedAmount=model.chargedAmount
			if(parseFloat(accumulateAmount)<parseFloat(chargedAmount)){
				return true;
			}
			return false;
		},
		//支付金额数据判断
		handlePayAmount(){
			let model=this.basicForm;
			let feeCategory=model.feeCategory
			let payAmount= Number(model.payAmount)
			if(feeCategory=="0"){//工资福利
					// if(payAmount>model.salaryFeeInfo.amount){
						if(payAmount> Number(model.accumulateAmount)){
						return true;
					}
			}else if(feeCategory=="1"){//采购
					if(payAmount> Number(this.$refs.purchaseRef.purchaseyFeeInfo.amount)){
						return true;
					}
			}else if(feeCategory=="2"){//费用类
					let data=this.$refs.costRef.costList;
					let amount=0;
					data.forEach(item=>{
						amount+=Number(item.amount);
					})
					amount=amount.toFixed(2);
					if(payAmount>amount){
						return true;
					}
			}
			return false;
		},
		//支付金额数据判断是否大于报销后的冲账剩余金额
		handlePayAndChargedAmount(){
			let model=this.basicForm;
			let feeCategory=model.feeCategory
			let payAmount=model.payAmount
			let accumulateAmount=model.accumulateAmount
			let chargedAmount=model.chargedAmount
			let unChargedAmount=(accumulateAmount-chargedAmount).toFixed(2)
			if(feeCategory=="0"){//工资福利
						if(parseFloat(payAmount)>parseFloat(unChargedAmount)){
						return true;
					}
			}else if(feeCategory=="1"){//采购
					if(parseFloat(payAmount)>parseFloat(unChargedAmount)){
						return true;
					}
			}else if(feeCategory=="2"){//费用类
					if(parseFloat(payAmount)>parseFloat(unChargedAmount)){
						return true;
					}
			}
			return false;
		},
		// 获取标题名称类型
		getTeamFeeCategoryTitle(){
			let feeCategory = ''
			switch (this.basicForm.feeCategory) {
				case '0': feeCategory = '工资福利类';break;
				case '1': feeCategory = '采购类';break;
				case '2': feeCategory = '费用类';break;
			}
			return feeCategory;
		},
		// 获取标题时间
		getCreateTime() {
			let createTime = this.basicForm.createTime;
			let date = createTime.substring(0,10)
			return date.substring(0,4) +'年'+ date.substring(5,7)+'月' + date.substring(8,10)+'日';
		},
    // 点击提交
    async onSubmit() {
			var _this = this
			if(this.basicForm.isPay==1&&!this.basicForm.payAmount) {
				this.showMessage('请输入本次付款金额!')
				return false
			}
			if(!this.basicForm.applyExplain) {
				this.showMessage('请输入报销说明!')
				return false
			}if(!this.basicForm.teamFeeCategory) {
				this.showMessage('请选择团队费用类别!')
				return false
			}
			if(!this.basicForm.postscript && this.basicForm.transferType && this.basicForm.accountName) {
				this.showMessage('请输入打款附言!')
				return false
			}
			if(this.handleAmount()){
				this.showMessage('本次冲账金额不能大于报销金额!')
				return false
			}
			if(this.handlePayAmount()){
				this.showMessage('本次付款金额不能大于报销金额!')
				return false
			}
			if(this.handlePayAndChargedAmount()){
				this.showMessage('本次付款金额不能大于报销金额冲账后的剩余金额!')
				return false
			}
			if (this.basicForm.feeCategory=='1') {
				let respon = await this.$refs.purchaseRef.onSubmit()
				if(!respon){
					return false
				}
			}
			let teamName = await filterMultiDictText(this.dictOptions['teamManager'], this.basicForm.teamId + '')
			let createTime = await this.getCreateTime()
			let teamFeeCategory = await this.getTeamFeeCategoryTitle()
			this.basicForm.bpmBizTitle = await (teamName? teamName+ ' - ':'') + this.userInfo?.employee?.name + ' - ' + createTime +  (this.basicForm.accumulateAmount? ' - ' + this.basicForm.accumulateAmount :'') + (teamFeeCategory? ' - ' + teamFeeCategory :'') //标题
			var params = this.basicForm
			let res = await feeReimburseEdit(params)
			if (res.success) {
			  this.$refs.uToast.show({
			  	message: '提交成功',
			  	type: 'success',
			  	complete () {
			  		_this.onAudit()
			  	}
			  })
			  this.isSubmit = true
			} else {
			  this.$refs.uToast.show({
			    message: res.message,
			    type: 'error',
			  })
			}
      // var params = this.basicForm
      // feeReimburseEdit(params).then((res) => {
      //   if (res.success) {
      //     this.$refs.uToast.show({
      //     	message: '提交成功',
      //     	type: 'success',
      //     	complete () {
      //     		_this.onAudit()
      //     	}
      //     })
      //     this.isSubmit = true
      //   } else {
      //     this.$refs.uToast.show({
      //       message: res.message,
      //       type: 'error',
      //     })
      //   }
      // })
    },

    onAudit() {
      if (!this.isSubmit) {
        uni.showToast({
          title: '请完善表单后审核',
          icon: 'none',
        })
        return false
      }
      var that = this
      uni.navigateTo({
        url: '/pages/synergy/erpFinanceReimbursementBillList' + `?item=${encodeURIComponent(JSON.stringify(this.model).replace(/%/g, '%25'))}`,
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          // acceptDataFromOpenedPage: function(data) {
          // }
        },
        success: function (data) {
          // 通过eventChannel向被打开页面传送数据
          var params = {
            nodeObj: encodeURIComponent(JSON.stringify(that.nodeObj).replace(/%/g, '%25')),
            tabvalue: that.tabvalue,
          }
          data.eventChannel.emit('sendMessage', params)
        },
        fail: function (err) {
          this.$refs.uToast.show({
            message: '请联系管理员配置',
            type: 'error',
          })
        },
      })
    },
  },
}
</script>

<style lang="scss" scoped>
@import url("@/assets/inputStyle.scss");
.basic-style {
  background: #ffffff;
  margin: 20rpx;
  border-radius: 20rpx;
  padding: 16rpx 32rpx;
  box-shadow: 0px 4px 20px 0px rgba(0, 0, 0, 0.1);
}
// 基本信息
.basic-title {
  font-size: 16px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 600;
  color: #333333;
  line-height: 44rpx;
  padding-bottom: 16rpx;
}
.basic-border {
  border-bottom: 1px solid #f2f2f2;
}
.basic-padding {
  padding-top: 16rpx;
}
</style>
